﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ClientSite2nd.Models;
using ClientSite2nd.Logic;

namespace ClientSite2nd.Controllers
{

    [Authorize]
    public class AccountController : Controller
    {

        //
        // GET: /Account/Index
        [Authorize]
        public ActionResult Index()
        {
            return View(SessionWrapper.CurrentClient);
        }

        [Authorize]
        public ActionResult EditProfile()
        {
            return View(SessionWrapper.CurrentClient);
        }

        [Authorize]
        [HttpPost]
        public ActionResult EditProfile(Client client, HttpPostedFileBase profileImage)
        {
            var sss = Request.IsAjaxRequest();
            if (ModelState.IsValid)
            {
                string imageUploadStatus;
                UpdateClientData(client, profileImage, out imageUploadStatus);
                ViewBag.StatusMsg = imageUploadStatus;
                return RedirectToAction("Index");
            }
            return View(client);
        }

        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login()
        {
            var loginModel = new LoginModel { Companies = Companies.All };

            return View(loginModel);
        }

        //
        // POST: /Account/Login

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {

            string fullUserName = string.Concat(model.UserName, "_", model.SelectedCompany);

            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(fullUserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(fullUserName, model.RememberMe);

                    if (!Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            var registerModel = new RegisterModel { Companies = Companies.All };
            return View(registerModel);

        }

        //
        // POST: /Account/Register

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            string fullUserName = string.Concat(model.UserName, "_", model.SelectedCompany);

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(fullUserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(fullUserName, createPersistentCookie: false);

                    var currentUser = Membership.GetUser(fullUserName);

                    CreateClient((Guid)currentUser.ProviderUserKey,
                                               model.UserName, model.Email, model.SelectedCompany); ;

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        
        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, userIsOnline: true);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        /// <summary>
        /// Creates new entity in client's profile table using some registration information from membership table
        /// </summary>
        /// <param name="providerUserKey"></param>
        /// <param name="userName"></param>
        /// <param name="email"></param>
        /// <param name="company"></param>
        private void CreateClient(Guid providerUserKey, string userName, string email, string company)
        {
            var clientContext = new ClientContext();

            Client client = new Client();
            client.Id = providerUserKey;
            client.Email = email;
            client.UserName = userName;
            client.Company = company;

            clientContext.Clients.Add(client);

            clientContext.SaveChanges();

        }

        /// <summary>
        /// Represents path to profile image
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public FileResult GetProfileImage()
        {
            return new FileContentResult(SessionWrapper.CurrentClient.ProfilePicture, "image");
        }

        /// <summary>
        /// Updates client's profile and membership data 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="profileImage"></param>
        /// <param name="status"></param>
        private void UpdateClientData(Client client, HttpPostedFileBase profileImage, out string status)
        {
            var clientContext = new ClientContext();

            Client newClient = clientContext.Clients.SingleOrDefault(c => c.Id == client.Id);

            newClient.Address = client.Address;
            newClient.BirthdayDate = client.BirthdayDate;
            newClient.FirstName = client.FirstName;
            newClient.LastName = client.LastName;
            status = string.Empty;
            if (profileImage != null)
            {
                newClient.ProfilePicture = PassProfilePicture(profileImage, out status);
            }

            SessionWrapper.Finagle();

            clientContext.SaveChanges();
        }

        /// <summary>
        /// Serialize profile picture
        /// </summary>
        /// <param name="profileImage"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private byte[] PassProfilePicture(HttpPostedFileBase profileImage, out string status)
        {
            const string typesNonFormatted = "image/jpeg,image/png,image/gif,image/bmp";
            string[] types = typesNonFormatted.Split(',');
            byte[] tempImage = null;

            if (profileImage.ContentLength == 0 || profileImage.ContentLength > 100000)
            {
                status =
                    "Could not upload: File too big (max size 100kb) or error while transfering the file.";
            }

            else if (types.Contains(profileImage.ContentType) == false)
            {
                status =
                    "Could not upload: incorrect file type!<br/> Allowed types: jpeg, png, gif, bmp.";
            }

            else
            {
                status = string.Concat("Uploaded: ", profileImage.FileName, " (", Convert.ToDecimal(profileImage.ContentLength) / 1000, " kb)");

                int length = profileImage.ContentLength;
                tempImage = new byte[length];
                profileImage.InputStream.Read(tempImage, 0, length);
            }
            return tempImage;
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

    }
}
